import React from 'react';
import { Form, Input, Button, message, Modal, InputNumber, Space, Tabs, Radio } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import moment from 'moment';

const currControl = 'Edu_Vaccines';
const { confirm } = Modal;
const { TabPane } = Tabs;

class VaccinesEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      imageUrl: '',
      imgList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { ParentData } = this.props;
    if (ParentData && ParentData.id) {
      this.getData(ParentData.id);
    }
  }
  getData = (id: number) => {
    const { dispatch } = this.props;
    if (id) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      }).then(() => {
        var result = this.props.response.result;
        console.log(result);
        result.isFree = result.isFree.toString();
        if (result.poster) {
          this.setState({ imageUrl: UploadUtil.imgServ + result.poster });
        }
        if (result.startTime) result.startTime = moment(result.startTime);
        if (result.endTime) result.endTime = moment(result.endTime);
        this.formRef.current.setFieldsValue({ model: result });
      });
    }
  };
  onFinish = async (values: any) => {
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    console.log(values);
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.props.fetchDatas();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas();
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  onChange = (value: number[]) => {
    this.setState({
      inputValue: value,
    });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      UploadUtil.getBase64(info.file.originFileObj, (imageUrl: any) =>
        this.setState({
          imageUrl,
          imgList: info.fileList,
          loading: false,
        }),
      );
    }
  };
  render() {
    const { datas, loading } = this.state;
    return (
      <div>
        <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本" key="1">
              <div style={{ display: 'none' }}>
                <Form.Item label="id" name={['model', 'id']}>
                  <Input />
                </Form.Item>
              </div>
              <Form.Item name={['model', 'name']} label="疫苗名称" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item name={['model', 'isFree']} label="是否免费"
                  rules={[{ required: true }]}
                >
                  <Radio.Group>
                    <Radio value="true">允许</Radio>
                    <Radio value="false">不允许</Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item name={['model', 'age']} label="适龄" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item
                    name={['model', 'minAge']}
                    label="接种最小年龄"
                  >
                    <InputNumber min={1} />
                  </Form.Item>
                  <Form.Item
                    name={['model', 'maxAge']}
                    label="接种最大年龄"
                  >
                    <InputNumber min={1} />
                  </Form.Item>
                </Input.Group>
              </Form.Item>
              <Form.Item name={['model', 'prevent']} label="可预防传染病">
                <Input.TextArea />
              </Form.Item>
              <Form.Item name={['model', 'attention']} label="注意事项">
                <Input.TextArea />
              </Form.Item>
              <Form.Item name={['model', 'introduction']} label="疫苗简介">
                <Input.TextArea />
              </Form.Item>
            </TabPane>
          </Tabs>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
              <Button onClick={this.ResetForm}>重设</Button>
              <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                删除
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(VaccinesEdit);
